package cn.iocoder.yudao.module.book.service.admin.bookshelf;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.book.controller.admin.bookshelf.vo.BookShelfPageReqVO;
import cn.iocoder.yudao.module.book.controller.admin.bookshelf.vo.BookShelfSaveReqVO;
import cn.iocoder.yudao.module.book.dal.dataobject.bookshelf.BookShelfDO;
import cn.iocoder.yudao.module.book.dal.mysql.bookshelf.BookShelfMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.SHELF_NOT_EXISTS;

/**
 * 绘本集 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class BookShelfServiceImpl implements BookShelfService {

    @Resource
    private BookShelfMapper shelfMapper;

    @Override
    public Long createShelf(BookShelfSaveReqVO createReqVO) {
        // 插入
        BookShelfDO shelf = BeanUtils.toBean(createReqVO, BookShelfDO.class);
        shelfMapper.insert(shelf);

        // 返回
        return shelf.getId();
    }

    @Override
    public void updateShelf(BookShelfSaveReqVO updateReqVO) {
        // 校验存在
        validateShelfExists(updateReqVO.getId());
        // 更新
        BookShelfDO updateObj = BeanUtils.toBean(updateReqVO, BookShelfDO.class);
        shelfMapper.updateById(updateObj);
    }

    @Override
    public void deleteShelf(Long id) {
        // 校验存在
        validateShelfExists(id);
        // 删除
        shelfMapper.deleteById(id);
    }

    @Override
    public void deleteShelfListByIds(List<Long> ids) {
        // 删除
        shelfMapper.deleteByIds(ids);
    }


    private void validateShelfExists(Long id) {
        if (shelfMapper.selectById(id) == null) {
            throw exception(SHELF_NOT_EXISTS);
        }
    }

    @Override
    public BookShelfDO getShelf(Long id) {
        return shelfMapper.selectById(id);
    }

    @Override
    public PageResult<BookShelfDO> getShelfPage(BookShelfPageReqVO pageReqVO) {
        return shelfMapper.selectPage(pageReqVO);

    }

    @Override
    public String getBookShelfNameById(Long bookShelfId) {
        BookShelfDO bookShelfDO = shelfMapper.selectById(bookShelfId);
        if (bookShelfDO == null) {
            return null;
        }
        return bookShelfDO.getTitle();
    }

}